#pragma once

#include <iostream>
#include <queue>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"
#include "Cond.hpp"


namespace BlockQueueModule
{
    using namespace LockModule;
    using namespace CondModule;
    static const int gcap = 10;
    template<class T>
    class BlockQueue
    {
    private:
        bool IsFull()
        {
            return _q.size() == _cap;
        }
        bool IsEmpty()
        {
            return _q.empty();
        }
    public:
        BlockQueue(int cap = gcap):_cap(cap),_cwait_num(0),_pwait_num(0)
        {
        }
        void Equeue(const T& in)
        {
            LockGuard lockguard(_mutex);
            while(IsFull())
            {
                std::cout << "生产者进入等待..." << std::endl;
                _pwait_num++;
                _productor_cond.Wait(_mutex);
                _pwait_num--;
                std::cout << "生产者被唤醒..." << std::endl;
            }
            _q.push(in);

            if(_cwait_num)
            {
                _consumer_cond.Notify();
            }
        }
        void Pop(T* out)
        {
            LockGuard lockguard(_mutex);
            while(IsEmpty())
            {
                std::cout << "消费者进入等待..." << std::endl;
                _cwait_num++;
                _consumer_cond.Wait(_mutex);
                _cwait_num--;
                std::cout << "消费者被唤醒..." << std::endl;
            }
            //到这里我们必定有数据
            *out = _q.front();
            _q.pop();

            //一定有空间
            if(_pwait_num)
            {
                _productor_cond.Notify();
            }
        }
        ~BlockQueue()
        {
        }
    private:
        std::queue<T> _q;              //保存数据的容器
        int _cap;                      //bq最大容量
        Mutex _mutex;        //互斥
        Cond _productor_cond;//生产者的条件变量
        Cond _consumer_cond; //消费者的条件变量

        int _cwait_num;
        int _pwait_num;
    };
}
